package com.androidlab.task1;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class PositionLoggerActivity extends Activity {

	private Button startServiceButton;
	private Button stopServiceButton;
	private Button updateButton;
	private Button exitButton;
	private service serviceProxy;
	private ServiceConnection serviceConnection;
	  /** boolean indicating whether the activity is bound to the service or not. */
	boolean isBound = false;
	  /**Boolean indicating whether the service has been stopped by the user. */
	boolean isStopped = false;
	double latitude;
	double longitude;
	double distance;
	double avgSpeed;
	Location lastLocation;
	long startTime;
	
    /** Called when the activity is first created. */
   
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initializeService();
        startServiceButton = (Button) findViewById(R.id.start_service_button);
        startServiceButton.setOnClickListener(startServiceButtonListener);
        stopServiceButton = (Button) findViewById(R.id.stop_service_button);
        stopServiceButton.setOnClickListener(stopServiceButtonListener);
        updateButton = (Button) findViewById(R.id.update_values_button);
        updateButton.setOnClickListener(updateButtonListener);
        exitButton = (Button) findViewById(R.id.exit_button);
        exitButton.setOnClickListener(exitButtonListener);
        startTime = System.currentTimeMillis();
       
    }
	 /** Called to initialize the underlying service */
    private void initializeService(){
    	Intent intent = new Intent();
    	intent.setClassName("com.androidlab.task1", "com.androidlab.task1.PositionLoggerService");
    	serviceConnection = new PositionLoggerServiceConnection();
    	bindService(intent,serviceConnection,Context.BIND_AUTO_CREATE);
    	
    }
    /** Called to invoke the service when the the "Start Service" button is pressed in the GUI */
    private void invokeService(){
    	TextView latTv = (TextView)findViewById(R.id.latitude_text);
    	TextView longTv = (TextView)findViewById(R.id.longitude_text);
    	TextView stepTv = (TextView)findViewById(R.id.step_text);

    	if(serviceProxy == null){

    		latTv.setText("Service not ready");
    		longTv.setText("Service not ready");
    	}
    	else{
    		// Variable indicating whether a binding exists to the service or not
    		isBound = true;

    		try {
				lastLocation = serviceProxy.updateLocation();
				latitude = lastLocation.getLatitude();
				longitude = lastLocation.getLongitude();
				
				latTv.setText(""+latitude);
	    		longTv.setText(""+longitude);
	    		stepTv.setText(""+serviceProxy.getSteps());
				
			} catch (RemoteException e1) {
				e1.printStackTrace();
			}
    	}
    }

    /** Method to stop the service, but only if the service already have been started. Called when the
     * user presses the "Stop Service" button */
    
    private void stopService(){
//      The "Stop Service" in the activity now retrieves the latest GPS coordinates. 
//      The GPX file will be automatically updated. This means that the last coordinates in the GPX 
//      file should be used for comparison with the results of the linear dead reckoning algorithm.
    	if(isBound){
			unbindService(serviceConnection);
		 	TextView latTv = (TextView)findViewById(R.id.latitude_text);
	    	TextView longTv = (TextView)findViewById(R.id.longitude_text);
	    	TextView deviationTv = (TextView)findViewById(R.id.deviation_text);
	    	latTv.setText("");
	    	longTv.setText("");
	    	
	    	try {
				Location newLocation = serviceProxy.updateLocation();
				latTv.setText(""+newLocation.getLatitude());
				longTv.setText(""+newLocation.getLongitude());
				deviationTv.setText(""+serviceProxy.getDistance());
			} 
	    	
	    	catch (RemoteException e) {
				e.printStackTrace();
			}
	    	
			isBound = false;
			isStopped = true;
			
			Intent svc = new Intent(this,PositionLoggerService.class);
			stopService(svc);
			}
    }
    
    private OnClickListener stopServiceButtonListener = new OnClickListener() {
    	
    	public void onClick(View v){
    		stopService();
    	}
    };
    private OnClickListener updateButtonListener = new OnClickListener() {
    	public void onClick(View v){
    		TextView stepTv = (TextView)findViewById(R.id.step_text);
	    	TextView azimuthTv = (TextView)findViewById(R.id.azimuth_text);

	    	
    		if(!isBound || isStopped){
    		}
    		else{

    			try {
    				stepTv.setText(""+serviceProxy.getSteps());
    				azimuthTv.setText(""+serviceProxy.getOrientation());
    			} 
    			catch (RemoteException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    };

    private OnClickListener startServiceButtonListener = new OnClickListener() {
  
    	public void onClick(View v){
    		
 // 	    If the service already have been running, but have been stopped - initialize the service again.
//    		If not, simply invoke the service.
    		if(isStopped){
    			initializeService();
    			isStopped = false;
    		}
    		invokeService();
   	}
    };
    private OnClickListener exitButtonListener = new OnClickListener() {
    	public void onClick(View v){
    		finish();
       	}
    };
    
    class PositionLoggerServiceConnection implements ServiceConnection
    {
		public void onServiceConnected(ComponentName arg0, IBinder boundService) {
			serviceProxy = service.Stub.asInterface(boundService);
		}

		public void onServiceDisconnected(ComponentName arg0) {
			serviceProxy = null;
		}
    };
}